package com.manong.config.security.filter;

import com.manong.config.redis.RedisService;
import com.manong.config.security.exception.CustomerAuthenticationException;
import com.manong.config.security.handler.LoginFailureHandler;
import com.manong.config.security.service.CustomerUserDetailsService;
import com.manong.utils.JwtUtils;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.springframework.security.core.AuthenticationException;
/**
 * token验证过滤器
 */
@Data
@Component
public class CheckTokenFilter extends OncePerRequestFilter {
    @Resource
    private RedisService redisService;
    @Resource
    private JwtUtils jwtUtils;
    @Resource
    private CustomerUserDetailsService customerUserDetailsService;
    @Resource
    private LoginFailureHandler loginFailureHandler;

    @Value("${request.login.url}")
    private String loginUrl;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            String url = request.getRequestURI();
            if(!url.equals(loginUrl)){
                this.validateToken(request);  //若不是登录请求，则进行token验证
            }
        } catch (AuthenticationException e) {
            loginFailureHandler.onAuthenticationFailure(request,response,e);
        }
        //放行
        doFilter(request,response,filterChain);
    }

    /**
     * 验证token
     * @param request
     */
    private void validateToken(HttpServletRequest request){

        String token = request.getHeader("token");
        if(ObjectUtils.isEmpty(token)){
            token = request.getParameter("token");  //若请求头中不存在token，则从参数中获取
        }
        if (ObjectUtils.isEmpty(token)){
            throw new CustomerAuthenticationException("token不存在");
        }

        String redisTokenKey = "token_"+token;
        String redisToken = redisService.get(redisTokenKey);
        if (ObjectUtils.isEmpty(redisToken)){
            throw new CustomerAuthenticationException("token已失效");
        }
        if(!redisToken.equals(token)){
            throw new CustomerAuthenticationException("token验证失败");
        }
        String usernameFromToken = jwtUtils.getUsernameFromToken(token);
        if (ObjectUtils.isEmpty(usernameFromToken)){
            throw new CustomerAuthenticationException("token验证失败");
        }
        UserDetails userDetails = customerUserDetailsService.loadUserByUsername(usernameFromToken);
        if (userDetails==null){
            throw new CustomerAuthenticationException("token验证失败");
        }
        //创建身份验证对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        //设置到Spring Security上下文
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
    }

}
